package com.security.test.config;

import com.security.test.filter.MyLoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class MyUsernamePasswordLoginConfig<H extends HttpSecurityBuilder<H>> extends AbstractAuthenticationFilterConfigurer<H, MyUsernamePasswordLoginConfig<H>, MyLoginFilter> {


    // 构造方法
    public MyUsernamePasswordLoginConfig() {
        super(new MyLoginFilter(), "/user/login");
    }

    // 默认初始化方法
    @Override
    public void init(H http) throws Exception {
        super.init(http);
    }

    // 主要的配置方法
    @Override
    public void configure(H http) throws Exception {
        // 添加认证提供者
        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        // 设置过滤器
        MyLoginFilter myUsernamePasswordAuthenticationFilter = this.getAuthenticationFilter();
        myUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManager);

        // 将filter添加到过滤器链中 SecurityFilterChain
        http.addFilterAfter(myUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }


    // 设置登录页面地址
    @Override
    public MyUsernamePasswordLoginConfig<H> loginPage(String loginPage) {
        return super.loginPage(loginPage);
    }

    // 设置认证URL
    @Override
    public MyUsernamePasswordLoginConfig<H> loginProcessingUrl(String loginProcessingUrl) {
        return super.loginProcessingUrl(loginProcessingUrl);
    }

    public MyUsernamePasswordLoginConfig<H> loginSuccessHandler(AuthenticationSuccessHandler handler) {
        (this.getAuthenticationFilter()).setAuthenticationSuccessHandler(handler);
        return this;
    }

    public MyUsernamePasswordLoginConfig<H> loginFailHandler(AuthenticationFailureHandler handler) {
        (this.getAuthenticationFilter()).setAuthenticationFailureHandler(handler);
        return this;
    }

    // 配置认证URL的RequestMatcher
    @Override
    protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
        return new AntPathRequestMatcher(loginProcessingUrl, "POST");
    }


}